import logging

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import Group
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q

# Create your views here.
from FasterRunner import settings
from fastuser.utils import try_login_ldap

User = get_user_model()
from FasterRunner.settings import logger


class CustomBackend(ModelBackend):
    """
    自定义用户验证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        # print("进入到了自定义验证函数。。。。。")
        # print("username:",username)
        # print("password:", password)
        # 先使用ldap登录验证
        # 1.如果验证通过，检查本地是否存在该账号，存在则返回该用户，如果不存在，则自动创建一个账户并且返回
        # 2.如果ldap登录验证失败，则本地登录验证。（兼容旧账号）
        if settings.LDAP_LOGIN_ENABLE  and try_login_ldap(username, password):
            logging.info("尝试使用ldap登录验证")
            try:
                user = User.objects.get(Q(username=username))
                return user
            except ObjectDoesNotExist:
                logging.info("获取本地username失败,自动注册新用户")
                user = User(username=username)
                user.set_password(password)
                user.save()
                # 给新注册用户默认分配到组"新注册默认组-组名固定"
                default_group = Group.objects.filter(name='新注册默认组-组名固定')
                if default_group:
                    group_users = [user]
                    default_group[0].user_set.add(*group_users)
                    # print("成功分配到默认组")
                # # 给新注册用户分配演示项目权限"演示项目"
                # default_project = Project.objects.filter(name__contains='演示项目')
                # if default_project:
                #     user.belong_project.add(*default_project)
                #     # print("成功分配到演示项目")
                return user
        else:
            logger.info("使用本地登录验证")
            try:
                user = User.objects.get(Q(username=username))
                if user.check_password(password):
                    return user
            except ObjectDoesNotExist:
                logger.info("获取本地username失败")
                return
